package com.cykj.admin.service.impl;

import com.cykj.admin.mapper.UserMapper;
import com.cykj.admin.service.IUserService;
import com.cykj.admin.vo.UserVO;
import com.cykj.common.dto.ResponseDTO;
import com.cykj.common.entity.UserDO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @BelongsProject:@BelonqsPackage:com.cykj.admin.service.impl
 * @Author:jiangna
 * @CreateTime:2025-08-16 11:26
 */
@Service
public class UserServiceImpl implements IUserService {
    @Value("${fileUrl}")
    private String fileUrl;

    @Autowired
    private UserMapper userMapper;

    /**
     * @Description: 获取所有用户的信息 / 根据条件查询用户信息
     * @Param: [userVO]
     * @return: com.cykj.common.dto.ResponseDTO
     */
    public ResponseDTO selectByCondition(UserVO userVO) {

        PageInfo<UserDO> page;
        //开启分页
        PageHelper.startPage(userVO.getCurrentPage(), userVO.getPageSize());
        List<UserDO> userList = userMapper.selectByCondition(userVO);
        for (UserDO userDO : userList) {
            if (!userDO.getHeadIcon().isEmpty()) {
                userDO.setHeadIcon(fileUrl + userDO.getHeadIcon());
            }
        }
        page = new PageInfo<>(userList);
        if (page.getTotal() < page.getPageSize() && userList.size() == 0 && page.getTotal() > 0) {
            userVO.setCurrentPage(1);
            PageHelper.startPage(userVO.getCurrentPage(), userVO.getPageSize());
            List<UserDO> userList2 = userMapper.selectByCondition(userVO);
            for (UserDO userDO : userList2) {
                if (!userDO.getHeadIcon().isEmpty()) {
                    userDO.setHeadIcon(fileUrl + userDO.getHeadIcon());
                }
            }
            page = new PageInfo<>(userList2);
        }
        return ResponseDTO.success(page);
    }

    /**
     * @Description: 重置用户密码
     * @Param: [userVO]
     * @return: com.cykj.common.dto.ResponseDTO
     */
    @Override
    public ResponseDTO resetPassword(Integer userId) {
        int result = userMapper.resetPassword(userId);
        if (result == 1) {
            return ResponseDTO.success();
        } else {
            return ResponseDTO.error("用户不存在或重置失败");
        }
    }

    /**
     * @Description: 封禁用户
     * @Param: [userVO]
     * @return: com.cykj.common.dto.ResponseDTO
     */
    @Override
    public ResponseDTO userBlock(UserVO userVO) {
        int result = userMapper.userBlock(userVO);
        if (result == 1) {
            return ResponseDTO.success();
        } else {
            return ResponseDTO.error("用户不存在或拉黑失败");
        }
    }
}
